from django.template import RequestContext
from django.shortcuts import render_to_response
from models import RSMUser
from RSM.util import verifySessionValidity, getUserNames, getRSMUser
    
def addFriend(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    li = getUserNames(RSMUser.objects.all())
    li.remove(request.user.username)
    for u in getUserNames(getRSMUser(request.user.username).friends.all()):
        li.remove(u)
    return render_to_response("my_friends/addfriend.html", {"users":li, "username": request.user.username}, context_instance=RequestContext(request))
   
def viewAllFriends(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
    
    username = request.user.username 
    friendsNames = [u.user.username for u in getRSMUser(username).friends.all()]
    hasToRemove = bool(len(friendsNames))
    hasToAdd = len(RSMUser.objects.all()) != len(friendsNames)+1
    return render_to_response("my_friends/viewfriends.html", {"friends": friendsNames, "hasToRemove": hasToRemove, "hasToAdd": hasToAdd}, context_instance=RequestContext(request))
     
def removeFriend(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag

    active_user = getRSMUser(request.user.username)
    for o in request.POST.getlist(u'friendsList'):
        friend = getRSMUser(o)
        active_user.friends.remove(friend)
        for gr in active_user.groups.all():
            if friend in gr.members.all():
                gr.members.remove(friend)
                
    friendsNames = [u.user.username for u in getRSMUser(request.user.username).friends.all()]
    hasToRemove = bool(len(friendsNames))
    hasToAdd = len(RSMUser.objects.all()) != len(friendsNames)+1
    return render_to_response("my_friends/viewfriends.html", {"friends": friendsNames, "hasToRemove": hasToRemove, "hasToAdd": hasToAdd}, context_instance=RequestContext(request))
    
def actualAdd(request):
    nonValidSessionFlag = verifySessionValidity(request)
    if nonValidSessionFlag:
        return nonValidSessionFlag
     
    active_user = getRSMUser(request.user.username)
    for o in request.POST.getlist(u'friendsToAdd'):
        friend = getRSMUser(o)
        active_user.friends.add(friend)
    friendsNames = [u.user.username for u in getRSMUser(request.user.username).friends.all()]
    hasToRemove = bool(len(friendsNames))
    hasToAdd = len(RSMUser.objects.all()) != len(friendsNames)+1
    return render_to_response("my_friends/viewfriends.html", {"friends": friendsNames, "hasToRemove": hasToRemove, "hasToAdd": hasToAdd}, context_instance=RequestContext(request))
